package gateway.config.knife4j;

import com.google.common.collect.Maps;
import common.util.Constants;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * knife4j接口文档配置
 *
 * @author 米泽鹏
 * @since 2022-11-23 下午 8:17
 */
@Primary
@Component
public class DocumentConfig implements SwaggerResourcesProvider, InitializingBean {

	private final Map<String, Integer> orderInfo = Maps.newHashMap();
	@Resource
	private ZuulProperties zuulProperties;

	/**
	 * 自定义文档顺序
	 */
	@Override
	public void afterPropertiesSet() {
		orderInfo.put("服务：game", 100);
		orderInfo.put("服务：system", 200);
		orderInfo.put("服务：log", 300);
		orderInfo.put("服务：gateway", 400);
	}

	@Override
	public List<SwaggerResource> get() {
		List<SwaggerResource> swaggerResourceList = new ArrayList<>();
		Map<String, ZuulProperties.ZuulRoute> routes = zuulProperties.getRoutes();
		// gateway服务
		SwaggerResource gatewaySwaggerResource = buildSwaggerResource(Constants.SERVICE_NAME_GATEWAY, "/v2/api-docs");
		swaggerResourceList.add(gatewaySwaggerResource);
		// log服务
		SwaggerResource logSwaggerResource = buildSwaggerResource(Constants.SERVICE_NAME_LOG, "/" + Constants.SERVICE_NAME_LOG + "/v2/api-docs");
		swaggerResourceList.add(logSwaggerResource);
		// zuul负责转发的下游服务
		for (String serviceName : routes.keySet()) {
			SwaggerResource swaggerResource = buildSwaggerResource(serviceName, "/" + serviceName + "/v2/api-docs");
			swaggerResourceList.add(swaggerResource);
		}
		// 排序
		swaggerResourceList.sort(Comparator.comparingInt(value -> orderInfo.getOrDefault(value.getName(), Integer.MAX_VALUE)));
		return swaggerResourceList;
	}

	private SwaggerResource buildSwaggerResource(String name, String url) {
		SwaggerResource swaggerResource = new SwaggerResource();
		swaggerResource.setSwaggerVersion(DocumentationType.SWAGGER_2.getVersion());
		swaggerResource.setName("服务：" + name);
		swaggerResource.setUrl(url);
		return swaggerResource;
	}

}
